﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;

namespace FlashPay.DAO.Impl
{
    using FlashPay.DAO.Interface;

    using FlashPay.EF;

    using FlashPay.Entity;
    using FlashPay.Entity.Parameter;
    using FlashPay.EF.Models;
    using System.Linq.Expressions;
    using FlashPay.Util;
    using FlashPay.DAO.Shared;
    using Microsoft.EntityFrameworkCore;
    using FlashPay.Entity.Response.Role;

    /// <summary>
    /// 系统角色数据接口实现
    /// </summary>
    /// <remarks>2018-07-09 immi 创建</remarks>
    public class SysRoleDaoImpl : BaseDAO, SysRoleDao
    {
        #region 注入
        /// <summary>
        /// EF上下文
        /// </summary>
        private FlashPayContext _context { set; get; }

        /// <summary>
        /// EF上下文
        /// </summary>
        private FlashPayContext _flashPayContext { set; get; }

        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="context"></param>
        public SysRoleDaoImpl(FlashPayContext context)
        {
            _context = (FlashPayContext)context;
        }

        public void Dispose()
        {
            if (_context != null)
            {
                _context.Dispose();
            }

            if (_flashPayContext != null)
            {
                _flashPayContext.Dispose();
            }
        }
        #endregion

        /// <summary>
        /// 根据编号获取系统角色
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>SysRole</returns>
        public SysRole Get(int id, FlashPayContext flashPayContext = null)
        {
            _flashPayContext = (flashPayContext ?? _context);
            return _flashPayContext.SysRole.Where(x => x.RId == id).FirstOrDefault();
        }

        /// <summary>
        /// 根据编号获取系统角色
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>SysRole</returns>
        public List<SysRole> GetByUserId(int userId, FlashPayContext flashPayContext = null)
        {
            _flashPayContext = (flashPayContext ?? _context);

            var roleIds = _flashPayContext.UserRole.Where(p => p.UrUid == userId).Select(p => p.UrRid).ToList();

            var roleList = _flashPayContext.SysRole.Where(p => roleIds.Contains(p.RId)).ToList();

            return roleList;
        }


        /// <summary>
        /// 获取用户角色
        /// </summary>
        /// <returns>List<UserRole></returns>
        public List<SysRole> GetByCompanyIds(List<int> ids, FlashPayContext flashPayContext = null)
        {
            _flashPayContext = (flashPayContext ?? _context);

            var roleList = _flashPayContext.SysRole.Where(x => ids.Contains(x.RCompanyId)).ToList();

            return roleList;
        }

        /// <summary>
        /// 根据编号获取用户(SQL)
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>UserInfo</returns>
        [Obsolete("废弃")]
        public SysRole GetUserInfo(int id)
        {
            var query = "SELECT * FROM SysRole WHERE uID = {0}";

            var userinfo = _context.SysRole
                .FromSql(query, id)
                .AsNoTracking()
                .SingleOrDefault();

            return userinfo;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="userInfo">新增对象</param>
        /// <returns></returns>
        public JResult<SysRole> Add(SysRole model, FlashPayContext flashPayContext = null)
        {
            var result = new JResult<SysRole>()
            {
                Success = false
            };

            try
            {
                _flashPayContext = (flashPayContext ?? _context);

                _flashPayContext.SysRole.Add(model);
                _flashPayContext.SaveChanges();

                result.Success = true;
                result.Data = model;
            }
            catch (Exception ex) {
                result.ErrorMessage = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="CardMerchant">修改对象</param>
        /// <returns></returns>
        public JResult<SysRole> Update(SysRole model, FlashPayContext flashPayContext = null)
        {
            var result = new JResult<SysRole>() {
                Success = false
            };

            try
            {
                _flashPayContext = (flashPayContext ?? _context);

                var role = _flashPayContext.SysRole.Find(model.RId);
                if (role != null)
                {
                    role.RName = model.RName;
                    _flashPayContext.SaveChanges();

                    result.Success = true;
                    result.Data = role;
                }
            }
            catch (Exception ex) {
                result.ErrorMessage = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id">系统编号</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public bool UpdateStatus(int id, SByte status)
        {
            //官方推荐的修改方式（先查询，再修改）
            var model = _context.SysRole.Where(p => p.RId.Equals(id)).FirstOrDefault();
            if (model != null)
            {
                model.RStatus = status;
                int row = _context.SaveChanges();
                return true;
            }
            else
            {
                throw new Exception("当前记录不存在！");
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">系统编号</param>
        /// <returns></returns>
        public bool Delete(int rId)
        {

            var model = _context.SysRole.Find(rId);
            if (model != null)
            {
                _context.SysRole.Remove(model);
                if (_context.SaveChanges() > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取所有用户记录
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>List<UserInfo></returns>
        public List<SysRole> GetList(SysRoleQuery query, FlashPayContext flashPayContext = null)
        {
            _flashPayContext = (flashPayContext ?? _context);

            //多条件查询
            var where = PredicateBuilder.True<SysRole>();
            //公司Id
            if (query.RId.HasValue)
            {
                where = where.And(c => c.RId == query.RId.Value);
            }
            //不等于角色Id
            if (query.NoEqualRId.HasValue)
            {
                where = where.And(c => c.RId != query.NoEqualRId.Value);
            }
            //公司Id
            if (query.CreateCID.HasValue)
            {
                where = where.And(c => c.CreateCid == query.CreateCID.Value);
            }
            //角色名称
            if (!string.IsNullOrEmpty(query.RName))
            {
                where = where.And(c => c.RName == query.RName);
            }
            //创建 人公司Id
            if (query.CreateCID.HasValue)
            {
                where = where.Or(c => c.CreateCid == c.RCompanyId);
            }
            var list = _flashPayContext.SysRole.Where(where.Compile()).ToList();
            return list;
        }

        /// <summary>
        /// 根据公司编号获取角色列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>List<UserInfo></returns>
        public List<SysRole> GetRoleByCompanyId(SysRoleQuery query)
        {
            var list = new List<SysRole>();

            var roles = _context.SysRole.Where(c =>c.RCompanyId == query.RoleCompanyId && c.CreateUid == query.CreateUId).ToList();
            if (roles != null && roles.Any()) {
                foreach (var item in roles)
                {
                    list.Add(item);
                }
            }

            return list;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<UserInfo></returns>
        public PagedList<SysRole> GetPager(SysRoleQuery query)
        {

            //多条件查询
            var where = PredicateBuilder.True<SysRole>();

            //公司编号
            where = where.And(c => query.CompanyIds.Contains(c.RCompanyId));

            //创建人编号
            if (query.CreateCID.HasValue)
            {
                where = where.And(c => c.CreateCid == query.CreateCID.Value);
            }
            //创建人编号
            if (query.CreateUId.HasValue)
            {
                where = where.And(c => c.CreateUid == query.CreateUId.Value);
            }
            //角色名称
            if (!string.IsNullOrEmpty(query.RName))
            {
                where = where.And(c => c.RName.Contains(query.RName));
            }

            //登录名称搜索
            if (!string.IsNullOrEmpty(query.RName))
            {
                where = where.And(c => c.RName.Contains(query.RName));
            }

            if (query.RStatus.HasValue)
            {
                where = where.And(c => c.RStatus == query.RStatus);
            }

            var row = _context.SysRole.Where(where.Compile()).OrderByDescending(p=>p.CreateDate).Skip((query.CurrentPageIndex.Value - 1) * query.PageSize.Value).Take(query.PageSize.Value).ToList();
            var count = _context.SysRole.Where(where.Compile()).Count();

            var list = new PagedList<SysRole>
            {
                TData = row,
                CurrentPageIndex = query.CurrentPageIndex.Value,
                TotalCount = count
            };

            return list;
        }

        /// <summary>
        /// 角色列表
        /// </summary>
        public void Get(BaseModel<List<SysRole>> result, SysRole model)
        {
            SysRole _model = model;

            /* 呼叫資料庫 */
            IQueryable<SysRole> _result = _context.SysRole.Where(
                role =>
                    role.RCompanyId == _model.RCompanyId &&
                    (_model.RId < 1 || role.RId == _model.RId)
            );

            List<SysRole> list = Split(_result.OrderByDescending(role => role.RId), result.PageIndex, result.PageSize);

            /* 結果複製 */
            result.Success = true;
            result.TotalCount = _result.Count();
            result.Result = list;
        }

        public List<SysRole> GetRoleByCompanyId(int companyId,FlashPayContext flashPayContext = null)
        {
            return _context.SysRole.Where(c => c.RCompanyId == companyId && c.CreateCid == companyId).ToList();
        }

        public List<SysRole> GetRoleByCreateIdAndCompanyId(int companyId,List<int> createIds, FlashPayContext flashPayContext = null)
        {
            //return _context.SysRole.Where(c => createIds.Contains(c.CreateUid) && c.RCompanyId == companyId).ToList();
            return _context.SysRole.Where(c => createIds.Contains(c.CreateUid)).ToList();
        }

        /// <summary>
        /// 获取角色的用户Id
        /// </summary>
        public List<UserInfo> GetRoleByUserId(int roleId,int roleCompanyId)
        {
            var query = $"SELECT * from UserInfo where uCompanyID={roleCompanyId} and uid in(select urUid from UserRole where urRid in(SELECT rid FROM SysRole where rid={roleId}))";

            var userinfo = _context.UserInfo
                .FromSql(query)
                .AsNoTracking()
                .ToList();

            return userinfo;
        }
    }
}
